﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Input;
using JDKD.BMCS.Business;
using JDKD.BMCS.Instruction;
using JDKD.BMCS.RenderBusiness;
using NutShell.DesignPattern;

namespace JDKD.BMCS.AppUI
{
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
                private BusinessCache cache = Singleton<BusinessCache>.Instance;

                private Thread renderThread;
                private Thread operationThread;

                public MainWindow()
                {
                        InitializeComponent();
                }

                private void Window_Loaded(object sender, RoutedEventArgs e)
                {
                        CameraRenderer.InitializeEnvironment();

                        
                        SerialPortCommunication.Initialize("COM2");

                        //工作线程启动
                        Singleton<BusinessCache>.Instance.Graphicses[1] = FirstPictureBox.CreateGraphics();
                        Singleton<BusinessCache>.Instance.Graphicses[2] = SecondPictureBox.CreateGraphics();
                        Singleton<BusinessCache>.Instance.Graphicses[3] = ThirdPictureBox.CreateGraphics();
                        Singleton<BusinessCache>.Instance.Graphicses[4] = FouthPictureBox.CreateGraphics();

                        renderThread = new Thread(RenderThreadFunction);
                        renderThread.Start();

                        operationThread = new Thread(OperationThreadFunction);
                        operationThread.Start();

                        LayoutRoot.DataContext = cache;
                }

                public static unsafe void RenderThreadFunction()
                {
                        BusinessCache bcache = Singleton<BusinessCache>.Instance;

                        int WaitingGraphicsCardIndex = 1;

                        for (; ; )
                        {
                                bcache.GraphicsCards[WaitingGraphicsCardIndex].UpdateSnapingFrameNumber();

                                if (bcache.GraphicsCards[WaitingGraphicsCardIndex].CompleteFrameIndex > -1)
                                {
                                        bcache.GraphicsCards[WaitingGraphicsCardIndex].TransformSnapImageData(bcache.Cameras[WaitingGraphicsCardIndex]);

                                        bcache.Cameras[WaitingGraphicsCardIndex].Analyse();

                                        CameraRenderer.Render(bcache.Graphicses[WaitingGraphicsCardIndex].GetHdc().ToPointer(), bcache.Cameras[WaitingGraphicsCardIndex]);
                                        bcache.Graphicses[WaitingGraphicsCardIndex].ReleaseHdc();

                                        bcache.GraphicsCards[WaitingGraphicsCardIndex].CompleteFrameIndex = -1;

                                        switch (WaitingGraphicsCardIndex)
                                        {
                                                case BusinessCache.CamerasCount:
                                                        WaitingGraphicsCardIndex = 1;
                                                        break;

                                                default:
                                                        WaitingGraphicsCardIndex++;
                                                        break;
                                        }
                                }

                                Thread.Sleep(5);
                        }
                }

                public static unsafe void OperationThreadFunction()
                {
                        BusinessCache bcache = Singleton<BusinessCache>.Instance;

                        for (; ; )
                        {
                                for (int i = 0; i < bcache.ShiftOperations.Count; i++)
                                {
                                        if (bcache.Channels.All(j => j.Value.ShiftState != ShiftState.已翻) && !bcache.Channels[bcache.ShiftOperations[i].Id].Group.IsPushing)
                                        {
                                                bcache.ShiftOperations[i].Run();

                                                bcache.ShiftOperations.RemoveAt(i);

                                                i = 0;
                                        }
                                }

                                Thread.Sleep(5);
                        }
                }

                private void ExitButton_Click(object sender, RoutedEventArgs e)
                {
                        Close();
                }

                private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
                {
                        renderThread.Abort();
                        operationThread.Abort();

                        SerialPortCommunication.UnInitialize();

                        foreach (var item in Singleton<BusinessCache>.Instance.GraphicsCards.Values)
                        {
                                item.StopSnapShotAsync();
                                item.StopGraphicsCard();
                        }
                }

                private void LoginStateTextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
                {
                        if (LoginStateTextBlock.Text == "未登录")
                        {
                                PasswordWindow window = new PasswordWindow();
                                window.ShowDialog();
                        }
                        else
                        {
                                cache.IsLogined = false;
                        }
                }

                private void FirstPictureBox_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                return;
                        }
                        PictureBoxMouseClick(1, e);
                }

                private void SecondPictureBox_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                return;
                        }
                        PictureBoxMouseClick(2, e);
                }

                private void ThirdPictureBox_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                return;
                        }
                        PictureBoxMouseClick(3, e);
                }

                private void FouthPictureBox_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                return;
                        }
                        PictureBoxMouseClick(4, e);
                }

                private void PictureBoxMouseClick(int cameraId, System.Windows.Forms.MouseEventArgs e)
                {
                        if (e.Button != MouseButtons.Left && e.Button != MouseButtons.Right)
                        {
                                return;
                        }

                        foreach (var item in Singleton<BusinessCache>.Instance.Cameras.Values)
                        {
                                item.UnHitTest();
                        }

                        if (e.Button != MouseButtons.Left)
                        {
                                return;
                        }

                        int x = (int)(e.X * 1.143);
                        int y = (int)(e.Y * 1.143);

                        cache.CurrentCamera = Singleton<BusinessCache>.Instance.Cameras[cameraId];
                        cache.CurrentArea = cache.CurrentCamera.HitTest(x, y);
                        if (cache.CurrentArea != null)
                        {
                                MainFrame.Source = null;
                                MainFrame.Navigate(new Uri("AreaPage.xaml", UriKind.Relative));
                                cache.OnPropertyChanged("CurrentArea");
                        }
                        else
                        {
                                MainFrame.Navigate(new Uri("CameraPage.xaml", UriKind.Relative));
                                cache.OnPropertyChanged("CurrentCamera");
                        }
                }

                private void RaiseButton_Click(object sender, RoutedEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                System.Windows.MessageBox.Show("请登录后执行此操作");
                                return;
                        }

                        new RaiseWindow().ShowDialog();
                }

                private void ShiftButton_Click(object sender, RoutedEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                System.Windows.MessageBox.Show("请登录后执行此操作");
                                return;
                        }
                        new ShiftWindow().ShowDialog();
                }

                private void PushButton_Click(object sender, RoutedEventArgs e)
                {
                        if (!cache.IsLogined)
                        {
                                System.Windows.MessageBox.Show("请登录后执行此操作");
                                return;
                        }
                        new PushWindow().ShowDialog();
                }

                
                
        }
}